

package system.communication;

import system.track.Sensor;

/**
 * This is a simple Threaded class which checks if the Monitor has sensor Messages,
 * and if it does it notifies the respective registered sensor(s) of the tripped status.
 * 
 * @author elliot
 */
public class SensorNotifier extends Thread
{
    private boolean running;

    /**
     * Default constructor
     */
    public SensorNotifier()
    {
        running = false;
    }
    
    /**
     * Starts the SensorNotifier thread to check if there are any Sensor Messages in
     * the ConcreteMonitor, if there are it compares the Sensor Messages values, which
     * are the id's of sensors, to the Registered sensors in the ConcreteMonitor. If the ids,
     * match then the sensor registered to the monitor has its tripped method called. This thread
     * is put to sleep for 1 millisecond per run to reduce redundant checks.
     */
    @Override
    public void run()
    {
        running = true;
        while(Monitor.getInstance().hasSensorMessage() && running)
        {
            Message topMessage = Monitor.getInstance().getSensorMessage();
            if(topMessage.getArg(MessageArg.SENSOR_VALUE_TWO) == null)
            {
                for(Sensor s : Monitor.getInstance().sensors)
                {
                    if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_ONE)))
                    {
                        s.tripped();
                    }    
                }
            }
            else
            {
                for(Sensor s : Monitor.getInstance().sensors)
                {
                    if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_ONE)))
                    {
                        s.tripped();
                    }
                    else if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_TWO)))
                    {
                        s.tripped();
                    }
                }
            }
            Monitor.getInstance().getMessageListener().sensorNotifierDeath();
            /*try
            {
                Thread.sleep(1);
            }
            catch (InterruptedException ex)
            {
                System.err.println(ex.getMessage());
                ex.printStackTrace();
            }*/
        }
    }

    /**
     * End method for the SensorNotifier
     */
    public synchronized void end()
    {
        running = false;
    }
}
